package com.genesis.yunnanji.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.genesis.yunnanji.R;
import com.genesis.yunnanji.activity.WebActivity;
import com.genesis.yunnanji.adapter.NewsAdapter;
import com.genesis.yunnanji.bean.BannerBean;
import com.genesis.yunnanji.bean.NewsBean;
import com.genesis.yunnanji.config.GenesisApiConfig;
import com.genesis.yunnanji.utils.GenesisUtils;
import com.genesis.yunnanji.utils.NetWorkUtils;
import com.google.gson.Gson;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.footer.LoadingView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

public class Information extends Fragment {
    private View view;
    private int page = 1;
    private List<NewsBean> newsBeanList;
    private List<NewsBean> todayList;
    private RecyclerView rvToday;
    private RecyclerView rvInfor;
    private TwinklingRefreshLayout refreshLayout;
    private NewsAdapter inforAdapter;
    private NewsAdapter todayAdapter;
    private List<BannerBean> bannerBeanList;
    private Banner mBanner;
    private GenesisUtils genesisUtils;

    public static Information newInstance(String param) {
        Information obj = new Information();
        Bundle bundle = new Bundle();
        bundle.putString("args1", param);
        obj.setArguments(bundle);
        return obj;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = this.getActivity().getLayoutInflater().inflate(R.layout.fragment_niformation, null);
            genesisUtils = GenesisUtils.getIntance();
            rvToday = (RecyclerView) view.findViewById(R.id.rv_information_today);
            rvInfor = (RecyclerView) view.findViewById(R.id.rv_information_news);
            refreshLayout = (TwinklingRefreshLayout) view.findViewById(R.id.bga_infor_refresh);
            mBanner = (Banner) view.findViewById(R.id.banner_information);
            initView();
            getTodayData(null);
            getData(null);
            getBannerData();
        } else {
            ViewGroup parent = (ViewGroup) view.getParent();
            if (parent != null) {
                parent.removeView(view);
            }
        }
        return view;
    }

    protected void initView() {
        newsBeanList = new ArrayList<>();
        todayList = new ArrayList<>();
        bannerBeanList = new ArrayList<>();
        rvInfor.addItemDecoration(new HorizontalDividerItemDecoration.Builder(Information.this.getActivity()).size((int) getResources().getDimension(R.dimen.x1)).color(Color.parseColor("#f5f5f5")).margin((int) getResources().getDimension(R.dimen.x1)).build());
        LoadingView loadingView = new LoadingView(this.getActivity());
        refreshLayout.setBottomView(loadingView);
        refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                page = 1;
                newsBeanList.removeAll(newsBeanList);
                todayList.removeAll(todayList);
                getData(refreshLayout);
                getTodayData(refreshLayout);
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                page += 1;
                getData(refreshLayout);
            }
        });
    }

    protected void setUpView() {

    }

    private void getData(final TwinklingRefreshLayout refreshLayout) {
        RequestParams params = new RequestParams(GenesisApiConfig.HOST + GenesisApiConfig.NEWS_LIST);
        params.addBodyParameter("categoryid", 94 + "");
        params.addBodyParameter("p", page + "");
        NetWorkUtils.doCacheGet(params, new NetWorkUtils.HttpResultListener() {
            @Override
            public void onSuccess(JSONObject jsonObject) {
                Log.e("ad",jsonObject.toString());
                Gson gson = new Gson();
                try {
                    JSONArray jsonArray = jsonObject.getJSONObject("result").getJSONArray("list");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        NewsBean newsBean = gson.fromJson(jsonArray.get(i).toString(), NewsBean.class);
                        newsBeanList.add(newsBean);
                    }
                    inforAdapter = new NewsAdapter(Information.this.getActivity(), newsBeanList);

                    rvInfor.setLayoutManager(new LinearLayoutManager(Information.this.getActivity()));
                    rvInfor.setNestedScrollingEnabled(false);
                    rvInfor.setAdapter(inforAdapter);
                    inforAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                            Intent intent = new Intent(Information.this.getContext(), WebActivity.class);
                            intent.putExtra("url", newsBeanList.get(position).getTaget_link() + "?__apptoken__=" + genesisUtils.getAppToken()+ "&from=app");
                            startActivity(intent);
                        }
                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void OnCached(JSONObject jsonObject) {
            }

            @Override
            public void onFinished() {
                if (refreshLayout != null) {
                    refreshLayout.finishRefreshing();
                    refreshLayout.finishLoadmore();
                }
            }

            @Override
            public void onError(String errorStr) {

            }
        });
    }

    private void getTodayData(final TwinklingRefreshLayout refreshLayout) {
        RequestParams params = new RequestParams(GenesisApiConfig.HOST + GenesisApiConfig.NEWS_LIST);
        params.addBodyParameter("categoryid", 93 + "");
        params.addBodyParameter("row", 3 + "");
        params.addBodyParameter("p", page + "");
        NetWorkUtils.doCacheGet(params, new NetWorkUtils.HttpResultListener() {
            @Override
            public void onSuccess(JSONObject jsonObject) {
                Gson gson = new Gson();
                try {
                    JSONArray jsonArray = jsonObject.getJSONObject("result").getJSONArray("list");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        NewsBean newsBean = gson.fromJson(jsonArray.get(i).toString(), NewsBean.class);
                        todayList.add(newsBean);
                    }
                    todayAdapter = new NewsAdapter(Information.this.getActivity(), todayList);
                    rvToday.addItemDecoration(new HorizontalDividerItemDecoration.Builder(Information.this.getActivity()).size((int) getResources().getDimension(R.dimen.x1)).color(Color.parseColor("#f5f5f5")).margin((int) getResources().getDimension(R.dimen.x1)).build());
                    rvToday.setLayoutManager(new LinearLayoutManager(Information.this.getActivity()));
                    rvToday.setNestedScrollingEnabled(false);
                    rvToday.setAdapter(todayAdapter);
                    todayAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                            Intent intent = new Intent(Information.this.getContext(), WebActivity.class);
                            intent.putExtra("url", todayList.get(position).getTaget_link()+ "?__apptoken__=" + genesisUtils.getAppToken()+ "&from=app");
                            startActivity(intent);
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void OnCached(JSONObject jsonObject) {
                Log.e("cache", jsonObject.toString());
            }

            @Override
            public void onFinished() {
                if (refreshLayout != null) {
                    refreshLayout.finishRefreshing();
                }
            }

            @Override
            public void onError(String errorStr) {

            }
        });
    }

    private void getBannerData() {
        RequestParams params = new RequestParams(GenesisApiConfig.HOST + GenesisApiConfig.BANNER);
        params.addBodyParameter("code", "app_news_banner");
        NetWorkUtils.doCacheGet(params, new NetWorkUtils.HttpResultListener() {
            @Override
            public void onSuccess(JSONObject jsonObject) {
                if (jsonObject.optInt("status")==200) {
                    mBanner.setVisibility(View.VISIBLE);
                    Gson gson = new Gson();
                    JSONArray jsonArray = null;
                    try {
                        jsonArray = jsonObject.getJSONObject("result").getJSONArray("list");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            BannerBean bannerBean = gson.fromJson(jsonArray.get(i).toString(), BannerBean.class);
                            bannerBeanList.add(bannerBean);
                        }
                        initBanner(bannerBeanList);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }else{
                    mBanner.setVisibility(View.GONE);
                }


            }

            @Override
            public void OnCached(JSONObject jsonObject) {
            }

            @Override
            public void onFinished() {

            }

            @Override
            public void onError(String errorStr) {
            }
        });
    }

    private void initBanner(List<BannerBean> list) {
        List<String> bannerimg = new ArrayList<>();
        final List<String> bannerUrl = new ArrayList<>();
        for (int j = 0; j < list.size(); j++) {
            bannerimg.add(list.get(j).getAdvert_img());
            bannerUrl.add(list.get(j).getTarget_link());
        }
        mBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Intent intent = new Intent(getContext(), WebActivity.class);
                intent.putExtra("url", bannerUrl.get(position));
                startActivity(intent);
            }
        });
        mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        mBanner.setImageLoader(new GlideImageLoader());
        mBanner.setIndicatorGravity(BannerConfig.RIGHT);
        mBanner.isAutoPlay(false);
        mBanner.setImages(bannerimg);
        mBanner.start();
    }

    class GlideImageLoader extends ImageLoader {


        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            /**
             注意：
             1.图片加载器由自己选择，这里不限制，只是提供几种使用方法
             2.返回的图片路径为Object类型，由于不能确定你到底使用的那种图片加载器，
             传输的到的是什么格式，那么这种就使用Object接收和返回，你只需要强转成你传输的类型就行，
             切记不要胡乱强转！
             */
            ImageOptions imageOptions = new ImageOptions.Builder().setImageScaleType(ImageView.ScaleType.FIT_XY).build();
            x.image().bind(imageView, GenesisApiConfig.PIC_HOST + (String) path, imageOptions);

        }

    }


}
